<?php

namespace App\Listeners;

use App\Allot;
use App\Events\OrderShipped;
use App\Income;
use App\SumIncome;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

class DistributeProfit
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderShipped $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        $order = $event->order;

        if ($order->isServiceOrder()) {
            return;
        }

        if ($order->isPaid()) {
            DB::transaction(function () use ($order) {
                $fee = $order->getPayFee();
                $orderNo = $order->order_no;
                $plats = Allot::get();
                foreach ($plats as $plat) {

//                    $oldCanFee = SumIncome::where(['user_id' => $plat->id])->first();
//                    $oldCanFee->update([
//                        'can_fee' => $plat->getProfit($fee),
//                    ]);


                    Income::create([
                        'admin_user_id' => $plat->id,
                        'fee' => $plat->getProfit($fee),
                        'order_no' => $orderNo
                    ]);

                }
            });
        }
    }
}
















